import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../large_data/CV2/lesson/Day03'
img_name = 'noisy1.png'
img_path1 = os.path.join(img_dir, img_name)

spr = 3
spc = 4
spn = 0
plt.figure(figsize=[8, 6])

sep('load')
img = cv.imread(img_path1, cv.IMREAD_GRAYSCALE)
print('original shape', img.shape)
H, W = img.shape
H2 = (H - 1) // 2
W2 = (W - 1) // 2
# my_show_img(img, 'original', cmap='gray')
img_ori = img.copy()

sep('threshold')
TH1 = 50
ret1, th1 = cv.threshold(img, TH1, 255, cv.THRESH_BINARY)
ret2, th2 = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
print(ret1, ret2)

sep('gaussian blur')
img = cv.GaussianBlur(img, (5, 5), 0)
img_gau = img.copy()

sep('threshold')
TH2 = 62
ret3, th3 = cv.threshold(img, TH2, 255, cv.THRESH_BINARY)
ret4, th4 = cv.threshold(img, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
print(ret3, ret4)

sep('plot')
plot_arr = [
    img_ori, img_ori, img_gau, img_gau
]
title_arr = [
    'ori', 'ori', 'GaussianBlur', 'GaussianBlur'
]
for img_data, title in zip(plot_arr, title_arr):
    my_show_img(img_data, title, cmap='gray')
for img_data in plot_arr:
    spn += 1
    plt.subplot(spr, spc, spn)
    plt.hist(img_data.ravel(), 256)
plot_arr = [
    th1, th2, th3, th4
]
title_arr = [
    'threshold ' + str(TH1), 'otsu', 'threshold ' + str(TH2), 'otsu'
]
for img_data, title in zip(plot_arr, title_arr):
    my_show_img(img_data, title, cmap='gray')

plt.show()
